<template>
  <div id="plant_list_edit">
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="信息" name="first">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="180px"
          class="demo-ruleForm"
        >
          <el-form-item label="编号：" prop="number">
            <el-input v-model="ruleForm.number" />
          </el-form-item>
          <el-form-item label="植物名：" prop="chinese_name">
            <el-input v-model="ruleForm.chinese_name" />
          </el-form-item>
          <el-form-item label="拉丁学名：" prop="latin_name">
            <el-input v-model="ruleForm.latin_name" />
          </el-form-item>
          <el-form-item label="别名：" prop="alias">
            <el-input v-model="ruleForm.alias" />
          </el-form-item>
          <el-form-item label="药材名：" prop="medicinal_name">
            <el-input v-model="ruleForm.medicinal_name" />
          </el-form-item>
          <el-form-item label="植物识别基础关键词：" prop="identify_key_words">
            <el-transfer
              v-model="ruleForm.identify_key_words"
              :titles="['植物识别列表', '选中植物识别']"
              :data="plant_recognition_class"
            />
          </el-form-item>
          <el-form-item label="文字描述：" prop="describe_info">
            <el-input
              v-model="ruleForm.describe_info"
              type="textarea"
              placeholder="请输入内容"
              rows="4"
              resize="none"
            />
          </el-form-item>
          <el-form-item label="花期和果期：" prop="flowering_and_fruiting">
            <el-input v-model="ruleForm.flowering_and_fruiting" />
          </el-form-item>
          <el-form-item label="地理分布：" prop="geographical">
            <el-transfer
              v-model="ruleForm.geographical"
              :titles="['省份列表', '选中省份']"
              :data="provinces_class"
            />
          </el-form-item>
          <el-form-item label="生境：" prop="living_environment">
            <el-input v-model="ruleForm.living_environment" />
          </el-form-item>
          <el-form-item label="应用部位：" prop="medicinal_parts">
            <el-checkbox-group v-model="ruleForm.medicinal_parts">
              <el-checkbox
                v-for="item in plant_parts"
                :key="item"
                :label="item"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="传统功效：" prop="traditional_efficacy_class">
            <el-checkbox-group v-model="ruleForm.traditional_efficacy_class">
              <el-checkbox
                v-for="item in traditional_efficacy_class"
                :key="item"
                :label="item"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="功效：" prop="effect">
            <el-checkbox-group v-model="ruleForm.effect">
              <el-checkbox
                v-for="item in ['清热药','抗疟，消热','清热燥湿，泻火解毒','祛风杀虫，通经止痛', '解毒，除湿，通利关节']"
                :key="item"
                :label="item"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="军事医学应用分类：" prop="military_medical_class">
            <el-checkbox-group v-model="ruleForm.military_medical_class">
              <el-checkbox
                v-for="item in military_medical_class"
                :key="item"
                :label="item"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="疾病分类：" prop="disease_name_class">
            <el-checkbox-group v-model="ruleForm.disease_name_class">
              <el-checkbox
                v-for="item in disease_name_class"
                :key="item"
                :label="item"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="适应症/用法：" prop="indication_usage">
            <el-input
              v-model="ruleForm.indication_usage"
              type="textarea"
              placeholder="请输入内容"
              rows="4"
              resize="none"
            />
          </el-form-item>
          <el-form-item label="军事应用分类：" prop="types_of_military_applications">
            <el-checkbox-group v-model="ruleForm.types_of_military_applications">
              <el-checkbox
                v-for="item in use"
                :key="item"
                :label="item"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="其他：">
            <el-input
              v-model="ruleForm.other"
              type="textarea"
              placeholder="请输入内容"
              rows="4"
              resize="none"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="next('ruleForm')"
            >下一步</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="图片" name="second">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-card class="box-card" header="手绘图">
              <el-upload
                class="upload-demo"
                action=""
                :file-list="hand_painted_url"
                :http-request="uploadImg0"
                :on-remove="handleRemove0"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card class="box-card" header="生境">
              <el-upload
                class="upload-demo"
                action=""
                :file-list="living_url"
                :http-request="uploadImg1"
                :on-remove="handleRemove1"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card" header="全株">
              <el-upload
                class="upload-demo"
                action=""
                :file-list="whole_plant_url"
                :http-request="uploadImg2"
                :on-remove="handleRemove2"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card" header="根">
              <el-upload
                class="upload-demo"
                action=""
                :file-list="root_url"
                :http-request="uploadImg3"
                :on-remove="handleRemove3"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card" header="茎">
              <el-upload
                class="upload-demo"
                action=""
                :file-list="stem_url"
                :http-request="uploadImg4"
                :on-remove="handleRemove4"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card" header="叶">
              <el-upload
                class="upload-demo"
                action=""
                :file-list="leaf_url"
                :http-request="uploadImg5"
                :on-remove="handleRemove5"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card" header="花">
              <el-upload
                class="upload-demo"
                action=""
                :file-list="flower_url"
                :http-request="uploadImg6"
                :on-remove="handleRemove6"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card" header="果实">
              <el-upload
                class="upload-demo"
                action=""
                :file-list="fruit_url"
                :http-request="uploadImg7"
                :on-remove="handleRemove7"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card" header="种子">
              <el-upload
                class="upload-demo"
                action=""
                :file-list="seed_url"
                :http-request="uploadImg8"
                :on-remove="handleRemove8"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-card>
          </el-col>
          <el-button
            type="primary"
            style="margin-left: 20px;"
            @click="submitForm"
          >保存</el-button>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { options } from '@/api/question'
import { upload, detail, upateById, deleteImg } from '@/api/plantList'
export default {
  data() {
    return {
      ruleForm: {
        number: '',
        chinese_name: '',
        latin_name: '',
        alias: '',
        medicinal_name: '',
        identify_key_words: [],
        describe_info: '',
        flowering_and_fruiting: '',
        geographical: [],
        living_environment: '',
        medicinal_parts: [],
        traditional_efficacy_class: [],
        effect: [],
        military_medical_class: [],
        disease_name_class: [],
        indication_usage: '',
        types_of_military_applications: [],
        other: ''
      },
      provinces_class: [],
      plant_recognition_class: [],
      rules: {
        number: [{ required: true, message: '请输入编号', trigger: 'blur' }],
        chinese_name: [{ required: true, message: '请输入中文名(植物名)', trigger: 'blur' }],
        latin_name: [{ required: true, message: '请输入拉丁学名', trigger: 'blur' }],
        alias: [{ required: true, message: '请输入别名', trigger: 'blur' }],
        medicinal_name: [{ required: true, message: '请输入药材名', trigger: 'blur' }],
        identify_key_words: [{ required: true, message: '请输入植物识别基础关键词', trigger: 'change' }],
        describe_info: [{ required: true, message: '请输入文字描述', trigger: 'blur' }],
        flowering_and_fruiting: [{ required: true, message: '请输入花期和果期', trigger: 'blur' }],
        geographical: [{ required: true, message: '请选择省份', trigger: 'change' }],
        living_environment: [{ required: true, message: '请输入生境', trigger: 'blur' }],
        medicinal_parts: [{ required: true, message: '请选择应用部位', trigger: 'change' }],
        traditional_efficacy_class: [{ required: true, message: '请选择传统功效', trigger: 'change' }],
        effect: [{ required: true, message: '请选择功效', trigger: 'change' }],
        military_medical_class: [{ required: true, message: '请选择军事医学应用分类', trigger: 'change' }],
        disease_name_class: [{ required: true, message: '请选择疾病分类', trigger: 'change' }],
        indication_usage: [{ required: true, message: '请输入适应症/用法', trigger: 'blur' }],
        types_of_military_applications: [{ required: true, message: '请选择军事应用分类', trigger: 'change' }],
      },
      activeName: 'first',
      hand_painted_url: [],
      living_url: [],
      whole_plant_url: [],
      root_url: [],
      stem_url: [],
      leaf_url: [],
      flower_url: [],
      fruit_url: [],
      seed_url: [],
      plant_parts: [],
      traditional_efficacy_class: [],
      military_medical_class: [],
      disease_name_class: [],
      use: [],
    }
  },
  mounted() {
    this.getOptions()
  },
  methods: {
    async getDetail() {
      const res = await detail(this.$route.params.id);
      if (res.code == 200) {
        for (const key in this.ruleForm) {
          if(key == 'geographical') {
            const geographical = res.data[key].split(',')
            const result = []
            this.ruleForm[key] = this.provinces_class.map(item => {
              geographical.map(val=> {
                if(val == item.label) {
                  result.push(item.key)
                }
              })
            })
            this.ruleForm.geographical = result
          } else if(key == 'identify_key_words') {
            const identify_key_words = res.data[key].split(',')
            const result = []
            this.ruleForm[key] = this.plant_recognition_class.map(item => {
              identify_key_words.map(val=> {
                if(val == item.label) {
                  result.push(item.key)
                }
              })
            })
            this.ruleForm.identify_key_words = result
          } else if(Object.prototype.toString.call(this.ruleForm[key]) == '[object Array]'){
            this.ruleForm[key] = res.data[key].split(',')
          } else {
            this.ruleForm[key] = res.data[key]
          }
        }
        const arr =  [
          'hand_painted_url', 
          'living_url',
          'whole_plant_url',
          'root_url',
          'stem_url',
          'leaf_url',
          'flower_url', 
          'fruit_url', 
          'seed_url'
        ]
        arr.map(item=> {
          const child =  res.data[item] && res.data[item].includes(',') ? res.data[item].split(',') : [res.data[item]]
          this[item] = child.map(val => ({
            id: val.split('imageid=')[1],
            url: val,
            uid: null
          }))
        })

      }
    },
    next(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.activeName = 'second'
        }
      })
    },
    submitForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const arr = []
          this.ruleForm.geographical.map(item=>{
            this.provinces_class.map(({key, label}) => {
              if(key == item) {
                arr.push(label)
              }
            })
          })
          const arr1 = []
          this.ruleForm.identify_key_words.map(item=>{
            this.plant_recognition_class.map(({key, label}) => {
              if(key == item) {
                arr1.push(label)
              }
            })
          })
          const params = {
            id: this.$route.params.id,
            number: this.ruleForm.number,
            chinese_name: this.ruleForm.chinese_name,
            latin_name: this.ruleForm.latin_name,
            alias: this.ruleForm.alias,
            medicinal_name: this.ruleForm.medicinal_name,
            identify_key_words: arr1.toString(),
            describe_info: this.ruleForm.describe_info,
            flowering_and_fruiting: this.ruleForm.flowering_and_fruiting,
            geographical: arr.toString(),
            living_environment: this.ruleForm.living_environment,
            medicinal_parts: this.ruleForm.medicinal_parts.toString(),
            traditional_efficacy_class: this.ruleForm.traditional_efficacy_class.toString(),
            effect: this.ruleForm.effect.toString(),
            military_medical_class: this.ruleForm.military_medical_class.toString(),
            disease_name_class: this.ruleForm.disease_name_class.toString(),
            indication_usage: this.ruleForm.indication_usage,
            types_of_military_applications: this.ruleForm.types_of_military_applications.toString(),
            other: this.ruleForm.other,
            hand_painted_url: this.hand_painted_url.map(item => item.id).toString(),
            living_url: this.living_url.map(item => item.id).toString(),
            whole_plant_url: this.whole_plant_url.map(item => item.id).toString(),
            root_url: this.root_url.map(item => item.id).toString(),
            stem_url: this.stem_url.map(item => item.id).toString(),
            leaf_url: this.leaf_url.map(item => item.id).toString(),
            flower_url: this.flower_url.map(item => item.id).toString(),
            fruit_url: this.fruit_url.map(item => item.id).toString(),
            seed_url: this.seed_url.map(item => item.id).toString()
          }
          upateById(params).then(res => {
            if (res.code == 200) {
              this.$message.success('保存成功')
              this.$router.push('/plantlib/list')
            }
          })
        } else {
          this.activeName = 'first'
        }
      })
    },
    async getOptions() {
      const res = await options()
      if (res.code == 200 && res.data) {
        const provinces_class = res.data.provinces_class
        this.provinces_class = provinces_class.map((element, index) => ({
          label: element,
          key: index
        }))

        const plant_recognition_class = res.data.plant_recognition_class
        this.plant_recognition_class = plant_recognition_class.map((element, index) => ({
          label: element,
          key: index
        }))
        this.plant_parts = res.data.plant_parts
        this.traditional_efficacy_class = res.data.traditional_efficacy_class
        this.military_medical_class = res.data.military_medical_class
        this.disease_name_class = res.data.disease_name_class
        this.use = res.data.use
      }
      this.getDetail()
    },
    // 图片上传
    async uploadImg0(item) {
      const formData = new FormData()
      formData.append('image_type', 0)
      formData.append('plant_number', this.ruleForm.number)
      formData.append('file', item.file)
      const res = await upload(formData)
      if (res.code == 200 && res.data) {
        this.hand_painted_url.push({
          url: res.data.url,
          uid: item.uid,
          id: res.data.id
        })
      }
    },
    async uploadImg1(item) {
      const formData = new FormData()
      formData.append('image_type', 1)
      formData.append('plant_number', this.ruleForm.number)
      formData.append('file', item.file)
      const res = await upload(formData)
      if (res.code == 200 && res.data) {
        this.living_url.push({
          url: res.data.url,
          uid: item.uid,
          id: res.data.id
        })
      }
    },
    async uploadImg2(item) {
      const formData = new FormData()
      formData.append('image_type', 2)
      formData.append('plant_number', this.ruleForm.number)
      formData.append('file', item.file)
      const res = await upload(formData)
      if (res.code == 200 && res.data) {
        this.whole_plant_url.push({
          url: res.data.url,
          uid: item.uid,
          id: res.data.id
        })
      }
    },
    async uploadImg3(item) {
      const formData = new FormData()
      formData.append('image_type', 3)
      formData.append('plant_number', this.ruleForm.number)
      formData.append('file', item.file)
      const res = await upload(formData)
      if (res.code == 200 && res.data) {
        this.root_url.push({
          url: res.data.url,
          uid: item.uid,
          id: res.data.id
        })
      }
    },
    async uploadImg4(item) {
      const formData = new FormData()
      formData.append('image_type', 4)
      formData.append('plant_number', this.ruleForm.number)
      formData.append('file', item.file)
      const res = await upload(formData)
      if (res.code == 200 && res.data) {
        this.stem_url.push({
          url: res.data.url,
          uid: item.uid,
          id: res.data.id
        })
      }
    },
    async uploadImg5(item) {
      const formData = new FormData()
      formData.append('image_type', 5)
      formData.append('plant_number', this.ruleForm.number)
      formData.append('file', item.file)
      const res = await upload(formData)
      if (res.code == 200 && res.data) {
        this.leaf_url.push({
          url: res.data.url,
          uid: item.uid,
          id: res.data.id
        })
      }
    },
    async uploadImg6(item) {
      const formData = new FormData()
      formData.append('image_type', 6)
      formData.append('plant_number', this.ruleForm.number)
      formData.append('file', item.file)
      const res = await upload(formData)
      if (res.code == 200 && res.data) {
        console.log(item)
        this.flower_url.push({
          url: res.data.url,
          uid: item.uid,
          id: res.data.id
        })
      }
    },
    async uploadImg7(item) {
      const formData = new FormData()
      formData.append('image_type', 7)
      formData.append('plant_number', this.ruleForm.number)
      formData.append('file', item.file)
      const res = await upload(formData)
      if (res.code == 200 && res.data) {
        this.fruit_url.push({
          url: res.data.url,
          uid: item.uid,
          id: res.data.id
        })
      }
    },
    async uploadImg8(item) {
      const formData = new FormData()
      formData.append('image_type', 8)
      formData.append('plant_number', this.ruleForm.number)
      formData.append('file', item.file)
      const res = await upload(formData)
      if (res.code == 200 && res.data) {
        this.seed_url.push({
          url: res.data.url,
          uid: item.uid,
          id: res.data.id
        })
      }
    },
    async handleRemove0(file, fileList) {
      const id = this.hand_painted_url.filter(item => item.id == file.id)[0].id
      this.hand_painted_url = this.hand_painted_url.filter(item => item.id != file.id)
      const res = await deleteImg(id)
      if (res.code == 200 && res.data) {
        this.$message.success('删除成功！')
      }
    },
    async handleRemove1(file, fileList) {
      const id = this.living_url.filter(item => item.id == file.id)[0].id
      this.living_url = this.living_url.filter(item => item.id != file.id)
      const res = await deleteImg(id)
      if (res.code == 200 && res.data) {
        this.$message.success('删除成功！')
      }
    },
    async handleRemove2(file, fileList) {
      const id = this.whole_plant_url.filter(item => item.id == file.id)[0].id
      this.whole_plant_url = this.whole_plant_url.filter(item => item.id != file.id)
      const res = await deleteImg(id)
      if (res.code == 200 && res.data) {
        this.$message.success('删除成功！')
      }
    },
    async handleRemove3(file, fileList) {
      const id = this.root_url.filter(item => item.id == file.id)[0].id
      this.root_url = this.root_url.filter(item => item.id != file.id)
      const res = await deleteImg(id)
      if (res.code == 200 && res.data) {
        this.$message.success('删除成功！')
      }
    },
    async handleRemove4(file, fileList) {
      const id = this.stem_url.filter(item => item.id == file.id)[0].id
      this.stem_url = this.stem_url.filter(item => item.id != file.id)
      const res = await deleteImg(id)
      if (res.code == 200 && res.data) {
        this.$message.success('删除成功！')
      }
    },
    async handleRemove5(file, fileList) {
      const id = this.leaf_url.filter(item => item.id == file.id)[0].id
      this.leaf_url = this.leaf_url.filter(item => item.id != file.id)
      const res = await deleteImg(id)
      if (res.code == 200 && res.data) {
        this.$message.success('删除成功！')
      }
    },
    async handleRemove6(file, fileList) {
      const id = this.flower_url.filter(item => item.id == file.id)[0].id
      this.flower_url = this.flower_url.filter(item => item.id != file.id)
      const res = await deleteImg(id)
      if (res.code == 200 && res.data) {
        this.$message.success('删除成功！')
      }
    },
    async handleRemove7(file, fileList) {
      const id = this.fruit_url.filter(item => item.id == file.id)[0].id
      this.fruit_url = this.fruit_url.filter(item => item.id != file.id)
      const res = await deleteImg(id)
      if (res.code == 200 && res.data) {
        this.$message.success('删除成功！')
      }
    },
    async handleRemove8(file, fileList) {
      const id = this.seed_url.filter(item => item.id == file.id)[0].id
      this.seed_url = this.seed_url.filter(item => item.id != file.id)
      const res = await deleteImg(id)
      if (res.code == 200 && res.data) {
        this.$message.success('删除成功！')
      }
    }
  }
}
</script>

<style scoped lang="scss">
.el-select{
  width: 100%;
}
.el-textarea, .el-input, .el-select{
  max-width: 582px;
}
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
</style>
<style lang="scss">
#plant_list_edit{
  .el-tabs--card>.el-tabs__header .el-tabs__item{
    font-size: 16px;
  }
  .el-tabs--card>.el-tabs__header .el-tabs__item.is-active{
    background-color: #f8fcff;
  }
  .el-card{
    margin-bottom: 20px;
  }
  .el-upload-list__item{
    float: left;
    margin-right: 20px;
    margin-bottom: 20px;
    width: 155px;
    height: 155px;
    img{
      width: 120px;
      height: 120px;
    }
  }
}
</style>
